import unittest

from tinydb.storage.lru import LRUCache

class LRUTest(unittest.TestCase):
    def test_lru(self):
        cache = LRUCache(2)

        cache.put(1, 1)
        cache.put(2, 2)
        self.assertEqual(cache.get(1), 1)    # returns 1
        cache.put(3, 3)   # evicts key 2
        self.assertEqual(cache.get(2), None)    # returns None (not found)
        cache.put(4, 4)   # evicts key 1
        self.assertEqual(cache.get(1), None)    # returns None (not found)
        self.assertEqual(cache.get(3), 3)    # returns 3
        self.assertEqual(cache.get(4), 4)    # returns 4

        self.assertEqual(str(cache.evicted), "[LRUNode(key=2, value=2, pinned=False), LRUNode(key=1, value=1, pinned=False)]")

        # 测试pin key=3
        cache.pin(3)
        cache.put(5, 5)   
        cache.put(6, 6)   
        self.assertEqual(cache.get(1), None)    # returns None (not found)
        self.assertEqual(cache.get(3), 3)    # returns 3
        self.assertEqual(cache.get(4), None)    # returns None (not found)

        # 测试unpin key=3
        cache.unpin(3)
        cache.put(7, 7)
        cache.put(8, 8)
        self.assertEqual(cache.get(3), None)    # returns None (not found)

if __name__ == '__main__':
    unittest.main()